package com.aldd.dao.impl;

import com.aldd.dao.FoodDao;
import com.aldd.entity.Food;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@Data
public class FoodDaoImpl implements FoodDao {
    @Override
    public Food selectFoodById(int id) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        DruidPooledConnection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        Food food = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from foods where food_id=" + id);
            while (resultSet.next()) {
                food = new Food(resultSet.getInt("food_id"), resultSet.getString("food_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return food;
    }

    @Override
    public int insertFood(Food food) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        DruidPooledConnection connection = null;
        Statement statement = null;
        int i = 0;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            i = statement.executeUpdate("insert into foods(food_name) values ('" + food.getFoodName() + "')");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;
    }
}
